package com.guxingke.typecho4j.jfinal.model;

import java.util.ArrayList;
import java.util.List;

import com.guxingke.typecho4j.Typecho4j;
import com.guxingke.typecho4j.util.DateUtil;
import com.guxingke.typecho4j.util.PageBean;
import com.guxingke.typecho4j.util.StringUtil;
import com.jfinal.plugin.activerecord.Model;

/**
 * typecho_options表 对应的model
 * */
public class Content extends Model<Content> {
	private static final long serialVersionUID = -4372440945143493207L;
	public static final Content dao = new Content();

	public List<Content> findAll() {
		return find("select * from typecho_contents");
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object get(String attr) {
		if ("created".equals(attr)) {
			return DateUtil.getDateFormatString(
					super.getLong(attr), Typecho4j
							.typecho4j()
							.getConstants()
							.getPostDataFormat());
		} else if ("text".equals(attr)) {
			return StringUtil.convertToHtml(super.getStr(attr));
		} else if ("textmd".equals(attr)) {
			return super.getStr("text");
		}
		return super.get(attr);
	}

	public List<Content> getPostsByMetaId(Long mid, PageBean pageBean) {
		// 1.获取postId 2. 获取对应的post
		String sql = "select c.cid from typecho_metas m left join typecho_relationships r on m.mid = r.mid left join typecho_contents c on c.cid = r.cid where m.mid = ? and c.type = 'post' order by created desc limit ?,?";
		List<Content> cids = find(sql, mid, pageBean.getStart(),
				pageBean.getPageSize());
		return getPostsByCids(cids);
	}

	public List<Content> getPostsByAuthorId(Long uid, PageBean pageBean) {
		// 1.获取postId 2. 获取对应的post
		String sql = "select cid from typecho_contents where type='post' and authorId=? order by created desc limit ?,?";
		List<Content> cids = find(sql, uid, pageBean.getStart(),
				pageBean.getPageSize());
		return getPostsByCids(cids);
	}

	private List<Content> getPostsByCids(List<Content> cids) {
		List<Content> results = new ArrayList<Content>();
		for (Content content : cids) {
			Content temp = getPostById(content.getLong("cid"));
			results.add(temp);
		}
		return results;
	}

	public Content getPostById(Long id) {
		Content post = Content.dao.findById(id);
		if (post == null || !"post".equals(post.get("type"))) {
			return null;
		}
		post.put("author", User.dao.findById(post.getLong("authorId")));
		post.put("categories",
				getCategoriesByContentId(post.getLong("cid")));
		post.put("tags", getTagsByContentId(post.getLong("cid")));
		return post;
	}

	public List<Meta> getCategoriesByContentId(Long contentId) {
		return Meta.dao.getCategoriesByContentId(contentId);
	}

	public List<Meta> getTagsByContentId(Long contentId) {
		return Meta.dao.getTagsByContentId(contentId);
	}

	public List<Content> getPosts(PageBean pageBean) {
		// 1.获取cid 2. 获取对应的post
		String sql = "select cid from typecho_contents where type = 'post' order by created desc limit ?,?";
		List<Content> cids = find(sql, pageBean.getStart(),
				pageBean.getPageSize());
		return getPostsByCids(cids);
	}

	public List<Content> getRecentPosts(int pageSize) {
		String sql = "select cid,title from typecho_contents where type = 'post' order by created desc limit 0,?";
		return find(sql, pageSize);
	}

	public List<Content> getFriendLinks() {
		String sql = "select * from typecho_contents where type = 'link'";
		return find(sql);
	}

	public List<Content> getPages() {
		String sql = "select * from typecho_contents where type='page'";
		return find(sql);
	}

	public Content getPageBySlug(String slug) {
		String sql = "select * from typecho_contents where type='page' and slug=?";
		return findFirst(sql, slug);
	}

	public Long getSearchPostsTotal(String keyword) {
		String sql = "select count(cid) as count from typecho_contents where type='post' and  (title LIKE ? OR text LIKE ?) group by type";
		String queryStr = "%" + keyword + "%";
		Content content = findFirst(sql, queryStr, queryStr);
		if (content == null) {
			return 0L;
		}
		return content.getLong("count");
	}

	public Long getAuthorPostsTotal(String prop) {
		String sql = "select count(cid) as count from typecho_contents where type='post' and  authorId=? group by type";
		Content content = findFirst(sql, prop);
		if (content == null) {
			return 0L;
		}
		return content.getLong("count");
	}

	public Long getTagPostsTotal(String prop) {
		return Meta.dao.getCountByMetaSlug(prop);
	}

	public Long getCategoryPostsTotal(String prop) {
		return Meta.dao.getCountByMetaSlug(prop);
	}

	public Long getArchivePostsTotal(String prop) {
		String[] temps = prop.split("-");
		int year = Integer.parseInt(temps[0]);
		int month = Integer.parseInt(temps[1]);
		Long start = DateUtil.getMonthFirstDay(year, month);
		Long end = DateUtil.getMonthFirstDay(year, month + 1);

		String sql = "select count(cid) as count from typecho_contents where type = 'post' and  created > ? and created < ? group by type";
		Content content = findFirst(sql, start, end);
		if (content == null) {
			return 0L;
		}
		return content.getLong("count");
	}

	public List<Content> getPostsByKeyword(String prop, PageBean pageBean) {
		// 1.获取cid 2. 获取对应的post
		String sql = "select cid from typecho_contents where type = 'post' and  (title LIKE ? OR text LIKE ?) order by created desc limit ?,?";
		String queryStr = "%" + prop + "%";
		List<Content> cids = find(sql, queryStr, queryStr,
				pageBean.getStart(), pageBean.getPageSize());
		return getPostsByCids(cids);
	}

	public Long getFirstCreatedTime() {
		String sql = "SELECT created as time FROM typecho_contents where type='post' order by created asc limit 0,1;";
		return findFirst(sql).getLong("time");
	}

	public List<Content> getPostsByArchiveInfo(String prop,
			PageBean pageBean) {
		String[] temps = prop.split("-");
		int year = Integer.parseInt(temps[0]);
		int month = Integer.parseInt(temps[1]);
		Long start = DateUtil.getMonthFirstDay(year, month);
		Long end = DateUtil.getMonthFirstDay(year, month + 1);
		String sql = "select cid from typecho_contents where type='post' and created > ? and created < ? order by created desc limit ?,?";
		List<Content> cids = find(sql, start, end, pageBean.getStart(),
				pageBean.getPageSize());
		return getPostsByCids(cids);
	}

	/*
	 * public List<Content> getPostsByAuthorName(String prop, PageBean
	 * pageBean) { Long authorId = User.dao.findUserIdByUsername(prop);
	 * return getPostsByAuthorId(authorId, pageBean); }
	 */

	public Long getCidBySlug(String slug) {
		String sql = "select cid from typecho_contents where slug = ?";
		return findFirst(sql, slug).getLong("cid");
	}

	public Long getUserIdByContentId(Long cid) {
		String sql = "select authorId from typecho_contents where cid = ?";
		return findFirst(sql, cid).getLong("authorId");
	}

	public void updateCommentsNum(Long cid) {
		Content content = findById(cid);
		content.set("commentsNum", content.getLong("commentsNum") + 1);
		content.update();
	}

	public Long getPublishedPostsNum() {
		String sql = "select count(cid) as count from typecho_contents where type = 'post' and  status='publish' group by type";
		Content result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getWaitingPostsNum() {
		String sql = "select count(cid) as count from typecho_contents where type = 'post' and  status='waiting' group by type";
		Content result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getDraftPostsNum() {
		String sql = "select count(cid) as count from typecho_contents where type = 'post' and  status='draft' group by type";
		Content result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getPublishedPagesNum() {
		String sql = "select count(cid) as count from typecho_contents where type = 'page' and  status='waiting' group by type";
		Content result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getDraftPagesNum() {
		String sql = "select count(cid) as count from typecho_contents where type = 'page' and  status='draft' group by type";
		Content result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Content getPage(Long cid) {
		String sql = "select * from typecho_contents where cid=?";
		return findFirst(sql, cid);
	}

	public List<Content> getAttachments() {
		String sql = "select * from typecho_contents where type='attachment'";
		return find(sql);
	}

}
